package RentCarProject;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.imageio.ImageIO;
import javax.sql.DataSource;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.Random;

public class AddCarPerformance {
    JFrame frame;
    JLabel countlabel,namelabel,colorlabel,typelabel,statuslabel,rentlabel,picturelabel;
    JTextField countField,nameField,colorField,typeField,statusField,rentField;
    MyButton addbutton,exitbutton;
    Car car;
    String address=null;
    public void init() throws Exception {
        frame=new JFrame("车辆入库");
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.setSize(900, 530);
        frame.setLocationRelativeTo(null);
        frame.setLayout(null);

        picturelabel=new JLabel();
        picturelabel.setBounds(550,70,260,260);
        picturelabel.setIcon(new ImageIcon("src/picture/addpicture.png"));
        picturelabel.setOpaque(false);

        countlabel =new JLabel("入库数量：");
        countlabel.setForeground(Color.white);
        countlabel.setFont(new Font("宋体", Font.BOLD,15));
        countlabel.setBounds(25,100,100,30);
        namelabel=new JLabel("车辆名称：");
        namelabel.setForeground(Color.white);
        namelabel.setFont(new Font("宋体", Font.BOLD,15));
        namelabel.setBounds(25,180,100,30);
        colorlabel=new JLabel("  颜色  ：");
        colorlabel.setForeground(Color.white);
        colorlabel.setFont(new Font("宋体", Font.BOLD,15));
        colorlabel.setBounds(25,260,100,30);
        typelabel=new JLabel("  车型  ：");
        typelabel.setForeground(Color.white);
        typelabel.setFont(new Font("宋体",Font.BOLD,15));
        typelabel.setBounds(275,100,100,30);
        statuslabel=new JLabel("车辆状态：");
        statuslabel.setForeground(Color.white);
        statuslabel.setFont(new Font("宋体",Font.BOLD,15));
        statuslabel.setBounds(275,180,100,30);
        rentlabel=new JLabel("  租金  ：");
        rentlabel.setForeground(Color.white);
        rentlabel.setFont(new Font("宋体",Font.BOLD,15));
        rentlabel.setBounds(275,260,100,30);

        countField =new JTextField();
        countField.setBounds(125,100,100,30);
        nameField=new JTextField();
        nameField.setBounds(125,180,100,30);
        colorField=new JTextField();
        colorField.setBounds(125,260,100,30);
        typeField=new JTextField();
        typeField.setBounds(375,100,100,30);
        statusField=new JTextField();
        statusField.setBounds(375,180,100,30);
        rentField=new JTextField();
        rentField.setBounds(375,260,100,30);


        addbutton =new MyButton("入库");
        addbutton.setBounds(120,380,100,40);
        addbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(countField.getText().isEmpty()||nameField.getText().isEmpty()||colorField.getText().isEmpty()||typeField.getText().isEmpty()||statusField.getText().isEmpty()||rentField.getText().isEmpty()){
                    JOptionPane.showMessageDialog(null,"车辆关键信息不能为空！");
                }else{
                    try {
                        if (statusField.getText().equals("1") || statusField.getText().equals("0")) {
                            Random rand=new Random();
                            int a=rand.nextInt(10000);
                            int m=Integer.parseInt(countField.getText());
                            for (int i = 0; i < m; i++) {
                                car = new Car();
                                while(searchCarbyid(a)){
                                    a=rand.nextInt(10000);
                                }
                                car.setId(a);
                                car.setName(nameField.getText());
                                car.setColor(colorField.getText());
                                car.setType(typeField.getText());
                                if (statusField.getText().equals("1")) {
                                    car.setState(true);
                                } else {
                                    car.setState(false);
                                }
                                car.setRent(Integer.parseInt(rentField.getText()));
                                car.setPicture(address);
                                try {
                                    addCarmessage(car);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                            JOptionPane.showMessageDialog(frame,"已成功入库"+m+"辆"+car.getColor()+car.getName()+"！");
                        } else {
                            JOptionPane.showMessageDialog(null, "车辆状态信息填写0（租出）或1（待租）！");
                        }
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        });
        exitbutton=new MyButton("退出");
        exitbutton.setBounds(330,380,100,40);
        exitbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
            }
        });


        JLabel label=new JLabel(new ImageIcon("src/picture/manageroperationui.png"));
        label.setBounds(0,0,900,530);
        label.setOpaque(false);
        MyButton browseButton = new MyButton("导入图片");
        browseButton.setBounds(600,360,160,50);
        browseButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browseAndUpload();
                try {//生成略缩图
                    BufferedImage originalImage = ImageIO.read(new File(address));
                    BufferedImage thumbnailImage = new BufferedImage(260,130,BufferedImage.TYPE_INT_ARGB);
                    Graphics2D graphics2D = thumbnailImage.createGraphics();
                    graphics2D.drawImage(originalImage.getScaledInstance(260,130,Image.SCALE_SMOOTH), 0,0,null);
                    graphics2D.dispose();
                    picturelabel.setIcon(new ImageIcon(thumbnailImage));
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        frame.add(picturelabel);
        frame.add(countlabel);
        frame.add(namelabel);
        frame.add(colorlabel);
        frame.add(typelabel);
        frame.add(statuslabel);
        frame.add(rentlabel);

        frame.add(countField);
        frame.add(nameField);
        frame.add(colorField);
        frame.add(typeField);
        frame.add(statusField);
        frame.add(rentField);

        frame.add(addbutton);
        frame.add(exitbutton);
        frame.add(browseButton);
        frame.add(label);
        frame.setVisible(true);
    }

    public boolean searchCarbyid(Object id) throws Exception {
        Properties properties=new Properties();
        properties.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(properties);
        Connection connection=dataSource.getConnection();
        String sql="select * from car where id=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setObject(1,id);
        ResultSet resultSet=preparedStatement.executeQuery();
        if(resultSet.next()){
            resultSet.close();
            preparedStatement.close();
            connection.close();
            return true;
        }else {
            resultSet.close();
            preparedStatement.close();
            connection.close();
            return false;
        }
    }

    public boolean addCarmessage(Car car) throws Exception {
        Properties properties=new Properties();
        properties.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource= DruidDataSourceFactory.createDataSource(properties);
        Connection connection=dataSource.getConnection();
        String sql="insert into car(id,name,color,type,status,rent,picture,addtime,count) values (?,?,?,?,?,?,?,current_time,0)";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setInt(1,car.getId());
        preparedStatement.setString(2,car.getName());
        preparedStatement.setString(3,car.getColor());
        preparedStatement.setString(4,car.getType());
        preparedStatement.setBoolean(5, car.getState());
        preparedStatement.setInt(6,car.getRent());
        preparedStatement.setString(7,car.getPicture());
        int i = preparedStatement.executeUpdate();
        preparedStatement.close();
        connection.close();
        if(i>0){
            return true;
        }else{
            return false;
        }
    }

    private void browseAndUpload() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int result = fileChooser.showOpenDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            address=file.getAbsolutePath();
            System.out.println(address);
            JOptionPane.showMessageDialog(frame,"导入图片成功！");
        }
    }

    public static void main(String[] args) throws Exception {
        new AddCarPerformance().init();
    }
}
